// MessageProvider.js
import React, { createContext, useContext, useState } from 'react';
import { message } from 'antd';

const MessageContext = createContext({
    success: () => {},
    error: () => {},
    warning: () => {},
    info: () => {},
});

export const MessageProvider = ({ children }) => {
    const [messageApi, contextHolder] = message.useMessage();

    console.log('messageApi:', messageApi); // 打印 messageApi

    const showMessage = (type, content, duration = 3) => {
        if (messageApi && messageApi.open) {
            messageApi.open({
                type,
                content,
                duration,
            });
        } else {
            console.error('messageApi.open is not defined');
        }
    };

    const messageActions = {
        success: (content, duration) => showMessage('success', content, duration),
        error: (content, duration) => showMessage('error', content, duration),
        warning: (content, duration) => showMessage('warning', content, duration),
        info: (content, duration) => showMessage('info', content, duration),
    };

    return (
        <MessageContext.Provider value={messageActions}>
            {contextHolder}
            {children}
        </MessageContext.Provider>
    );
};

// 导出 useMessage
export const useMessage = () => useContext(MessageContext);
